<template>
  <div class="cart-layout">
    <!-- 左侧固定导航栏 -->
    <div class="sidebar">
      <div class="logo">图书管理系统</div>
      <el-menu
        :default-active="activeMenu"
        class="sidebar-menu"
        router
      >
        <el-menu-item index="/books">
          <el-icon><Reading /></el-icon>
          <span>图书列表</span>
        </el-menu-item>
        <el-menu-item index="/cart">
          <el-icon><ShoppingCart /></el-icon>
          <span>购物车</span>
          <el-badge 
            v-if="cartCount > 0" 
            :value="cartCount" 
            :max="99" 
            class="badge" 
          />
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容区域 -->
    <div class="main-content">
      <router-view />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { cartAPI } from '@/api/cart'
import { Reading, ShoppingCart } from '@element-plus/icons-vue'

const route = useRoute()
const cartCount = ref(0)

// 当前激活的菜单项（新增）
const activeMenu = computed(() => route.path)

// 获取购物车数量
const fetchCartCount = async () => {
  try {
    const { data } = await cartAPI.getCartList()
    cartCount.value = data.reduce((total: number, cart: any) => {
      return total + (cart.cartItemList || []).reduce(
        (sum: number, item: any) => sum + item.quantity, 0
      )
    }, 0)
  } catch (error) {
    console.error('获取购物车数量失败', error)
  }
}

onMounted(() => {
  fetchCartCount()
})
</script>

<style scoped>
.cart-layout {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 220px;
  background: #fff;
  border-right: 1px solid #e6e6e6;
  box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.1);
  position: fixed;
  height: 100vh;
  z-index: 1000;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #e6e6e6;
}

.sidebar-menu {
  border-right: none;
  padding-top: 10px;
}

.main-content {
  flex: 1;
  margin-left: 220px; /* 与侧边栏宽度一致 */
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.badge {
  margin-left: 8px;
}

.el-menu-item {
  height: 50px;
  line-height: 50px;
  margin: 5px 0;
}

.el-menu-item.is-active {
  background-color: #ecf5ff;
  color: #409eff;
  border-right: 3px solid #409eff;
}

.el-icon {
  margin-right: 8px;
  font-size: 18px;
}
</style>